package com.kaifamiao.tcp;
import java.io.*;
import java.net.*;

public class FileServer {
    public final static int PORT = 12345;
    public final static String SAVE_PATH = "/Users/linrui/b/";

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("Server started. Waiting for connection...");

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new ClientHandler(socket)).start();
        }
    }
}

class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            System.out.println("Accepted connection : " + socket);

            DataInputStream dis = new DataInputStream(socket.getInputStream());
            while (true) {
                boolean isDirectory = dis.readBoolean();
                String entryName = dis.readUTF();

                if (entryName.equals("END")) break; // 结束传输的标志

                if (isDirectory) {
                    new File(FileServer.SAVE_PATH + entryName).mkdirs();
                } else {
                    long fileSize = dis.readLong();
                    FileOutputStream fos = new FileOutputStream(FileServer.SAVE_PATH + entryName);
                    byte[] buffer = new byte[4096];
                    int read = 0;
                    long remaining = fileSize;
                    while((read = dis.read(buffer, 0, (int)Math.min(buffer.length, remaining))) > 0) {
                        remaining -= read;
                        fos.write(buffer, 0, read);
                    }
                    fos.close();
                }
            }
            dis.close();
            socket.close();
            System.out.println("Transfer from " + socket.getRemoteSocketAddress() + " completed!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
